package org.example.my_netty.worker;


import org.example.my_netty.MyNettyContext;
import org.example.my_netty.myNettyHandlerChain.MyNettyHandler;

import java.nio.channels.SelectionKey;


//工作池 里面是多个worker 对标线程池里面的线程
public class MyWorkerGroup {

    //一个server的全局handler链 自己new好  目前只有读的  写的还更简单 不搞了
    public MyNettyContext context=new MyNettyContext();


    //添加链
    public void addHandler(MyNettyHandler handler){
        context.addHandler(handler);
    }

    // 可以分配channel进来
    private final MyWorker[] workers;

    //默认是五个
    public MyWorkerGroup() {
        this(5);
    }

    public MyWorkerGroup(int size) {
        workers = new MyWorker[size];
        for (int i = 0; i < size; i++) {
            workers[i]=new MyWorker();
            workers[i].setContext(context);
        }
    }

    private int index=0;


    //选择分配到哪个worker 默认是用轮询
    private MyWorker selectWorker(){
        System.out.println("选择worker"+index);
        return workers[index++%workers.length];
    }



    //根据传进来的key 启动
    public void start(SelectionKey key) {
        MyWorker worker = selectWorker();
        worker.start(key);
    }

}
